import {createRouter, createWebHistory,createWebHashHistory} from 'vue-router'
import Home from '@/views/Home.vue';
import Login from '@/views/login'
import Index from '@/views/index'
import About  from '@/views/About'
//import Menu from '@/views/sys/Menu'
import store from '@/store/index'

export const routes = [
    {
        path: '/',
        name: 'Index',
        component: Login
    },
    {
        path: '/index',
        name: 'Index',
        component: Index,
        children:[{
          path: 'home',
          name: 'Home',
          component: Home
        }]
    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/about',
        name: 'About',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: About,

    }
]

const router = createRouter({
	//base:'/WMSUI/',
   // history: createWebHistory(process.env.BASE_URL),
    history: createWebHashHistory('/WMSUI/'),
  // mode:'hash',
  mode:'history',
    routes
})

// router.beforeEach((to, from, next) => {
//     console.log(to.path);
//     if (to.path === '/login') {
//         next()
//     } else {
// 		console.log(store.state.DUser.realName)
//         if (store.state.DUser.id.length === 0) {
//             // store.dispatch('GenerateRoutes').then((data) => {
//             //     console.log('路由钩子')
//             //     console.log(data);
//             //     let accessRoutes = createNewRoutes(data)
//             //     console.log(accessRoutes);
//             //     // for (let i = 0; i < accessRoutes.length; i++){
//             //     //     console.log(accessRoutes[i]);
//             //     //     router.addRoute(accessRoutes[i])
//             //     // }
//             //     if(accessRoutes.length>0){
//             //         router.addRoute(accessRoutes[0])
//             //     }
//             //     next({...to, replace: true})
//             // }).catch((err) => {
//             //     console.log(err);
//             // });
// 		//	store.dispatch('GetInfo');
// 			next();
//         } else {
// 			//store.dispatch('LogOut');
//             next()
//         }
//     }
// })


function createNewRoutes(menuListData) {
    let routes = [];

    for (let i = 0; i < menuListData.length; i++) {
        let menuList = menuListData[i];
        let menuListChildren = menuList.children;
        for (let j = 0; j < menuListChildren.length; j++) {
            let menu = menuListChildren[j];
            //解析path
            let pathStrs = menu.url.split('/').filter((str) => {
                if (str.length > 0) {
                    return true
                }
            })
            if (pathStrs.length >= 2) {

               if( router.hasRoute(pathStrs[0])) {

                 //  router.addRoute(pathStrs[0].toString(),{path: pathStrs[1], name: menu.id, component: loadView(menu.url)});
               }else {
                   router.addRoute({path: '/' + pathStrs[0], name: pathStrs[0], component: Index,
                     //  children:{path: pathStrs[1], name: menu.id, component: loadView(menu.url)}
                   });

               }
                router.addRoute(pathStrs[0],{path: pathStrs[1], name: menu.id, component: loadView(menu.url)});
                // let route = {path: '', name: '', component: ''}
                // route.path = pathStrs[1];
                // route.name = menu.id;
                // if (menu.url) {
                //     route.component = loadView(menu.url);
                // } else {
                //     route.component = Index;
                // }
                //
                //
                // let bool = false;
                // for (let k = 0; k < routes.length; k++) {
                //     let rout = routes[k];
                //     if (rout.name == (pathStrs[0])) {
                //         bool = true
                //         rout.children.push(route);
                //     }
                // }
                // if (!bool) {
                //     routes = routes.concat([{
                //         path: '/' + pathStrs[0],
                //         name: pathStrs[0],
                //         component: Index,
                //         children: new Array(route)
                //     }])
                // }

            }

        }
    }
    return routes
}

function loadView(view) { // 路由懒加载
   // return (resolve) => require([`@/views/sys/user.vue`], resolve);
    //   return () => import([`@/views/${view}.vue`])
    return () => Promise.resolve(require(`@/views/${view}`).default)
}


const whiteList = ['/login', '/auth-redirect', '/bind', '/register']
/*
router.beforeEach((to, from, next) => {
//  NProgress.start()
  if (true) {
    /!* has token*!/
    if (to.path === '/login') {
      next({ path: '/login' })
 //     NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(res => {
          // 拉取user_info
          const roles = res.roles
          store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            Message.error(err)
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    //  NProgress.done()
    }
  }
})

*/
router.afterEach(() => {
    // NProgress.done()
})


export default router
